package blackberry.util.demo;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;

public class DjAppTimeLimit{
	
	private static final String DEFAULT_FOLDER = "file:///store/home/user/";
	private FileConnection fc;
	private long startTime;
	private long finishTime;
	private boolean endMark;
	
	public DjAppTimeLimit(String fileName, long currentTime, long limitTime) throws IOException {
		fc = openFileConnection(fileName);
		if (fc.exists() == false) {
			writeMarkFile(currentTime, limitTime, false);
		}
	}

	public boolean isAvailableTime() throws IOException{
		updateData();
		if (isEndMark()) 
			return false;
		if (checkTimeOut(System.currentTimeMillis())) {
			registerEndMark();			
			return false;
		}
		return true;
	}
	
	boolean isEndMark() throws IOException {
		return endMark;
	}
	
	private void registerEndMark() throws IOException{
		fc.delete();
		writeMarkFile(startTime, finishTime, true);
	}
	
	void updateData() throws IOException{
		DataInputStream in = fc.openDataInputStream();
		startTime = in.readLong();
		finishTime = in.readLong();
		endMark = in.readBoolean();
		in.close();
	}
	
	public long readStartTimes() throws IOException {
		updateData();
		return startTime;
	}

	public long readFinishTimes() throws IOException {
		updateData();
		return finishTime;
	}
	
	
	static boolean isExistFile(String fileName) throws IOException{
		FileConnection fc = (FileConnection) Connector.open(getFileURL(fileName));
		return fc.exists();
	}
	
	public static void deleteData(String fileName) throws IOException{
		FileConnection fc = (FileConnection) Connector.open(getFileURL(fileName));
		if (fc.exists())
			fc.delete();
	}
	
	static FileConnection openFileConnection(String fileName) throws IOException {
		return (FileConnection) Connector.open(getFileURL(fileName));
	}
	
	
	private void writeMarkFile(long startTime, long limitTime, boolean endMark) throws IOException {
		fc.create();
		fc.setHidden(true);
		DataOutputStream out = fc.openDataOutputStream();
		out.writeLong(startTime);
		out.writeLong(startTime + limitTime);
		out.writeBoolean(endMark);
		out.close();
	}
	
	private static String getFileURL(String fileName){
		return DEFAULT_FOLDER.concat(fileName);
	}
	
	private boolean checkTimeOut(long currentTime) throws IOException {
		return currentTime < readStartTimes() || currentTime > readFinishTimes();
	}
}